package qc.module.platform.service;

import com.alibaba.excel.util.StringUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.exception.QCPromptException;
import qc.module.platform.dto.user.UserContactDto;
import qc.module.platform.dto.user.UserContactQueryConditionDto;
import qc.module.platform.entity.QcDeptUser;
import qc.module.platform.entity.QcUserProject;
import qc.module.platform.entity.QcUsers;
import qc.module.platform.repository.QcUsersRepository;

import java.util.List;

/**
 * @projectName: qcdp
 * @package: qc.module.platform.service
 * @className: UserContactService
 * @version: 1.0
 */

@Service
public class UserContactService {

    private QcUsersRepository qcUsersRepository;

    @Autowired
    public void setQcUsersRepository(QcUsersRepository qcUsersRepository) {
        this.qcUsersRepository = qcUsersRepository;
    }


    /**
     * 查询用户联系信息
     *
     * @param condition: 查询条件
     * @return List<UserContactDto>  查询结果集
     * @author QcCheng Tech
     * @date 2023/10/9
     */
    public List<UserContactDto> query(UserContactQueryConditionDto condition) throws QCPromptException {
        //1.判断查询条件是否为空
        if (condition == null) {
            throw new QCPromptException("查询条件不能为空");
        }
        //2.判断项目编码是否为空
        if (StringUtils.isBlank(condition.getProject())) {
            throw new QCPromptException("查询条件项目编码不能为空");
        }
        //3.使用联合查询
        MPJLambdaWrapper<QcUsers> wrapper = new MPJLambdaWrapper<>();
        //指定查询内容
        wrapper.select(QcUsers::getId, QcUsers::getName, QcUsers::getPhone, QcUsers::getCornet, QcUsers::getTel, QcUsers::getDuty);
        //查询条件：为指定项目下的用户
        wrapper.eq(QcUserProject::getProjectcode, condition.getProject());
        wrapper.innerJoin(QcUserProject.class, QcUserProject::getUserid, QcUsers::getId);

        //判断是否查询部门下的用户
        if (!StringUtils.isBlank(condition.getDept())) {
            wrapper.eq(QcDeptUser::getDeptid, condition.getDept());
            wrapper.innerJoin(QcDeptUser.class, QcDeptUser::getUserid, QcUsers::getId);
        }
        //关键字查询，关键字可以是：用户名称，手机号，短号，办公室/座机号码，职务
        if (StringUtils.isNotBlank(condition.getWords())) {
            wrapper.and(q ->
                    q.like(QcUsers::getName, condition.getWords()).or().like(QcUsers::getPhone, condition.getWords()).or()
                            .like(QcUsers::getCornet, condition.getWords()).or().like(QcUsers::getTel, condition.getWords()).or()
                            .like(QcUsers::getDuty, condition.getWords())
            );
        }
        //排序，先按序号再按姓名进行升序排序
        wrapper.orderByAsc(QcUsers::getOdr, QcUsers::getName);
        //返回映射结果集
        return qcUsersRepository.selectJoinList(UserContactDto.class, wrapper);
    }
}
